﻿using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using RotovapPlatform.UI.ViewModels.Navigation;
using System.Diagnostics;
using System;
using RotovapPlatform.UI.Navigation;
using System.Windows.Media;
using System.Windows;
using System.Windows.Input;

namespace RotovapPlatform.UI.Views.Navigation;

public partial class SideMenuView : UserControl
{
	private readonly NavigationViewModel _viewModel;

	public SideMenuView()
	{
		InitializeComponent();
		_viewModel = App.ServiceProvider.GetRequiredService<NavigationViewModel>();
		DataContext = _viewModel;
	}

	private void NavigationListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
	{
		try
		{
			if (sender is ListBox currentListBox && currentListBox.SelectedItem is ListBoxItem item)
			{
				// 清除其他 ListBox 的选择
				ClearOtherListBoxSelections(currentListBox);

				if (item.Tag is NavigationItem navigationItem)
				{
					Debug.WriteLine($"Navigation requested: {navigationItem}");
					_viewModel.NavigateTo(navigationItem);
				}
				else
				{
					Debug.WriteLine($"无法识别的导航项类型: {item.Tag?.GetType().Name ?? "null"}");
				}
			}
		}
		catch (Exception ex)
		{
			Debug.WriteLine($"导航选择变更处理失败: {ex.Message}");
		}
	}

	private void ClearOtherListBoxSelections(ListBox currentListBox)
	{
		// 查找所有其他 ListBox 并清除它们的选择
		var parentItemsControl = VisualTreeHelper.GetParent(currentListBox) as DependencyObject;
		while (parentItemsControl != null && !(parentItemsControl is ItemsControl))
		{
			parentItemsControl = VisualTreeHelper.GetParent(parentItemsControl);
		}

		if (parentItemsControl is ItemsControl itemsControl)
		{
			foreach (var expander in LogicalTreeHelper.GetChildren(itemsControl).OfType<Expander>())
			{
				var listBox = expander.Content as ListBox;
				if (listBox != null && listBox != currentListBox)
				{
					listBox.SelectedItem = null;
				}
			}
		}
	}

	private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
	{
		ScrollViewer scrollViewer = (ScrollViewer)sender;
		if (e.Delta < 0)
		{
			scrollViewer.LineDown();
		}
		else
		{
			scrollViewer.LineUp();
		}
		e.Handled = true;
	}
}